package cn.uniqueinfo.dp.controller.base;

import cn.uniqueinfo.dp.enums.CtrlMethodEnum;
import cn.uniqueinfo.dp.exception.UQException;
import cn.uniqueinfo.dp.service.base.IBaseService;
import cn.uniqueinfo.dp.util.PermissionUtil;
import cn.uniqueinfo.dp.util.ResultUtil;
import cn.uniqueinfo.dp.util.ValidUtil;
import cn.uniqueinfo.dp.vo.BaseVO;
import cn.uniqueinfo.dp.vo.EasyuiTableResult;
import cn.uniqueinfo.dp.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * @author:朱元勋
 * @mail:395910063@qq.com
 * @date:2019-01-04 14:25:02
 * @description:控制器基类
 */
@Slf4j
public class BaseController<T extends BaseVO> {

    /** 服务 */
    protected IBaseService<T> baseService;
    /** 控制器名称对应权限前缀 */
    protected String ctlName = "";
    /** 控制器操作提示名前缀 */
    protected String tipName = "";

    /**
     * @author:朱元勋
     * @date:2019/1/9 13:56
     * @description: 权限验证
     * @param: type 操作方法
     * @param permission 权限
     * @return:void
     */
    protected void checkPermission(String type, String permission) {
        log.info("当前操作:" + type + ",对应权限点" + ctlName + ":" + permission);
        // PermissionUtil.checkPermission(this.ctlName,type,permission);
    }

    /** 默认首页访问 */
    @GetMapping(value = {"/", "/index"})
    public ModelAndView index() {
        this.checkPermission("index", "index");
        return new ModelAndView("/" + ctlName + "/index");
    }

    /** 新增 */
    @PostMapping(value = "/add")
    @ResponseBody
    public Result add(@Valid T item, BindingResult bindingResult) {
        return onAdd(item, "add", bindingResult);
    }

    protected Result onAdd(@Valid T item, String type, BindingResult bindingResult) {
        this.checkPermission(type, "add");
        if (bindingResult.hasErrors()) {
            String errorInfo = ValidUtil.errorInfo(bindingResult);
            throw new UQException(CtrlMethodEnum.ADD_ERR, errorInfo);
        }
        try {
            this.baseService.insert(item);
            return ResultUtil.success(item.getId());
        } catch (Exception e) {
            throw new UQException(CtrlMethodEnum.ADD_ERR, "", e);
        }
    }

    /** 修改 */
    @PostMapping("/edit")
    @ResponseBody
    public Result edit(@Valid T item, BindingResult bindingResult) {
        return onEdit(item, "edit", bindingResult);
    }

    protected Result onEdit(@Valid T item, String type, BindingResult bindingResult) {
        this.checkPermission("edit", "edit");
        if (bindingResult.hasErrors()) {
            String errorInfo = ValidUtil.errorInfo(bindingResult);
            throw new UQException(CtrlMethodEnum.EDIT_ERR, errorInfo);
        }
        try {
            this.baseService.update(item);
            return ResultUtil.success();
        } catch (Exception e) {
            throw new UQException(CtrlMethodEnum.EDIT_ERR, "", e);
        }
    }

    /** 获取对象 */
    @GetMapping(value = "/get/{id}")
    @ResponseBody
    public Result<T> get(@PathVariable Long id) {
        this.checkPermission("get", "get");
        try {
            if (id <= 0) {
                throw new UQException(CtrlMethodEnum.GET_ERR, "参数不合法id:" + id);
            }
            T item = this.baseService.findOneById(id);
            if (item == null) {
                throw new UQException(CtrlMethodEnum.GET_ERR, "找不到对象id:" + id);
            } else {
                return ResultUtil.success(item);
            }
        } catch (Exception e) {
            throw new UQException(CtrlMethodEnum.GET_ERR, "", e);
        }
    }
    /** 删除对象 */
    @PostMapping(value = "/del/{ids}")
    @ResponseBody
    public Result del(@PathVariable String ids) {
        this.checkPermission("del", "del");
        try {
            if (ids == null || ids.trim().length() == 0) {
                throw new UQException(CtrlMethodEnum.DEL_ERR, "参数不合法");
            }
            this.baseService.deleteByIds(ids);
            return ResultUtil.success();
        } catch (Exception e) {
            throw new UQException(CtrlMethodEnum.DEL_ERR, "", e);
        }
    }

    /** 获取对象列表 */
    @GetMapping(value = "/list")
    @ResponseBody
    public List<T> list(T item) {
        this.checkPermission("list", "list");
        return this.baseService.findAll(item);
    }

    /** 保存操作，融合新增和删除 */
    @PostMapping(value = "/save")
    @ResponseBody
    public Result save(@Valid T item, BindingResult bindingResult) {
        if (item.getId() == 0) {
            return onAdd(item, "save", bindingResult);
        } else {
            return onEdit(item, "save", bindingResult);
        }
    }

    /** 分页查询 */
    @GetMapping(value = "/page")
    @ResponseBody
    public EasyuiTableResult<T> page(T item, Integer page, Integer rows) {
        log.info("page:" + page + ",rows:" + rows);
        return this.baseService.findPage(item, page, rows);
    }
}
